<?php

namespace App\Services;

use App\Agency;
use App\BookApply;
use App\Document;
use App\Extensions\Widgets\EBox;
use App\PatentApply;
use App\PlantVariety;
use App\Repositories\BookApplyRepository;
use App\Repositories\PatentApplyRepository;
use App\Transverse;
use Encore\Admin\Admin;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Table;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class DashboardService
{

    public function transverseCharts(): string
    {
        if (!config('settings.module.project_module')) {
            return '';
        }
        $row = new Row();
        $title = '横向课题';
        $pieStyles = [
            'height' => '300px',
            'border' => '1px solid #d8d8d8'
        ];
        $list1 = Transverse::query()->select(DB::raw('review_status,state,tag,count(*) as count'))->groupBy(['review_status', 'state', 'tag'])->get();
        $data1 = [
            '审批中'     => $list1->where('review_status', 0)->sum('count'),
            '审批通过'   => $list1->where('review_status', 1)->sum('count'),
            '审批未通过' => $list1->where('review_status', 2)->sum('count'),
            '已结项'     => $list1->where('review_status', 1)->where('state', 1)->sum('count'),
            '已登记'     => $list1->where('tag', 1)->sum('count'),
        ];
        $row->column(6, $this->pie(sprintf('横向课题（共计：%s）', $list1->sum('count')), $data1, $pieStyles));
        $model = Transverse::query()->select(DB::raw('sum(amount)  as amount,sum(in_amount) as in_amount'))
            ->where('review_status', 1)
            ->first();
        $amount = $model['amount'] ?? 0;
        $in_amount = $model['in_amount'] ?? 0;
        $out_amount = $amount - $in_amount;
        $data2 = [
            '到账(万)'   => $in_amount,
            '未到帐（万）' => $out_amount
        ];
        $row->column(6, $this->pie(sprintf('合同金额(共计：%s万)', $amount), $data2, $pieStyles));
        $box = new Box($title, $row);
        return $box->solid()->style('primary')->render();
    }

    public function applying($user): string
    {
        $module = config('settings.module', []);
        $data = [];
        if (!empty($module['patent_module'])) {
            $count = PatentApply::query()->where('user_id', $user['id'])->where('review_status', 0)->count();
            $data[] = [
                $this->linkLabel(admin_route('patent.applies.index', ['action' => 'reviewing']), '专利申请前登记', ''),
                $count
            ];
        }
        if (!empty($module['software_module'])) {
            $count = BookApply::query()->where('user_id', $user['id'])->where('review_status', 0)->count();
            $data[] = [
                $this->linkLabel(admin_route('bookApplies.index', ['action' => 'reviewing']), '软著申请前登记', ''),
                $count
            ];
        }
        if (!empty($module['plant_module'])) {
            $count = PlantVariety::query()->where('user_id', $user['id'])->where('review_status', 0)->count();
            $data[] = [
                $this->linkLabel(admin_route('plantVarieties.index', ['action' => 'reviewing']), '植物新品种申请前登记', ''),
                $count
            ];
        }
        if (!empty($module['project_module'])) {
            $count = Transverse::query()->where('user_id', $user['id'])->where('review_status', 0)->count();
            $data[] = [
                $this->linkLabel(admin_route('transverses.index', ['action' => 'reviewing']), '横向课题申请', ''),
                $count
            ];
        }
        $table = new Table(['名称', '审批中'], $data);
        $box = new EBox('我的申请', $table);
        return $box->solid()->style('danger')->scrollable(['height' => '300px']);
    }

    public function applying2($user): string
    {
        $module = config('settings.module', []);
        $data = [];
        if (!empty($module['patent_module'])) {
            $data[] = [
                $this->linkLabel(admin_route('patent.applies.index', ['is_review' => 1]), '专利申请前登记审批', ''),
                app(PatentApplyRepository::class)->deptReviewCount($user, 0)
            ];
        }
        if (!empty($module['software_module'])) {
            $data[] = [
                $this->linkLabel(admin_route('bookApplies.index', ['action' => 'review']), '软件著作申请前审批', ''),
                app(BookApplyRepository::class)->deptReviewCount($user, 0)
            ];
        }
        $table = new Table(['名称', '待审批'], $data);
        $box = new EBox('科室待办', $table);
        return $box->solid()->style('danger')->scrollable(['height' => '300px']);
    }

    public function agency(): string
    {
        $module = config('settings.module', []);
        if (empty($module['patent_module'])) {
            return '';
        }
        $list = Agency::query()->where('role_type', 4)->orderBy('order')->get(['company', 'name', 'mobile', 'address']);
        $table = new Table(['代理机构', '联系人', '联系电话', '地址'], $list->toArray());
        $box = new EBox('合作代理机构', $table);
        return $box->solid()->style('info');
    }

    public function documents($user, array $config = []): string
    {
        $role = data_get($config, 'role', 0);
        $documents = Document::query()
            ->where('type', 0)
            ->when($role != 1, function ($query) use ($user) {
                $query->whereIn('department_id', [0, $user['department_id']]);
            })->orderByDesc('id')->get();
        return Admin::component('admin.dashboard.document', compact('documents', 'config'));
    }

    protected function linkLabel($href, $name, $blank = '_blank'): string
    {
        return sprintf('<a href="%s" target="%s">%s</a>', $href, $blank, $name);
    }

    protected function downloadLabel($href, $name, $download = null, $icon = 'download'): string
    {
        $download = $download ?: $name;
        if ($icon) {
            $name = sprintf('<i class="fa fa-%s"></i>&nbsp;', $icon) . $name;
        }
        return sprintf('<a href="%s" target="_blank" download="%s">%s</a>', $href, $download, $name);
    }

    public function pie($title, array $data, $styles = [])
    {
        $id = Str::random(50);
        $style = collect($styles)->map(function ($value, $key) {
            return $key . ':' . $value;
        })->implode(";");
        return view('chartjs.pie', compact('id', 'title', 'data', 'style'));
    }


}
